<style lang="less">
    @import "drawerParty.less";
    .s1{
        .ivu-select-dropdown-list {
            height:200px
        }
        .ivu-select-selected-value{
            color: black;
        }
    }



</style>
<template>
    <div class="search">
        <Row>
            <Col>
                <Card>
                    <Row>
                        <Spin fix v-if="spinShow">
                            <Icon type="ios-loading" size=60 class="demo-spin-icon-load"></Icon>
                            <div>请稍后...</div>
                        </Spin>
                        <h2 align="center">开票方信息</h2>
                        <div style="height: 50px" >

                            <Button  @click="back" size="large" type="primary" style="margin-right: 24px;float: right">返回
                            </Button>



                            <Button :loading="submitLoading" @click="checkFileMethed"
                                    v-if="this.typeCode != '0'" size="large"  type="primary" style="margin-right: 24px;float: right">提交
                            </Button>

                            <Button :loading="submitLoading" @click="saveDrawerParty"
                                    v-if="this.typeCode != '0'" size="large"  type="primary" style="margin-right: 24px;float: right">保存
                            </Button>

                            <!--<Button @click="addBlackList" v-if="this.typeCode == '0'"
                                    size="large"  type="primary" style="margin-right: 24px;width: auto;float: right">黑名单申请
                            </Button>-->

                        </div>


                        <br>
                        <br>

                        <Modal :title="modalTitle" v-model="blackApplyVisible" :mask-closable='false' :width="500" :styles="{top: '100px'}">
                            <Form ref="blackApplyForm" :model="blackApplyForm" :label-width="70" :rules="blackApplyFormValidate">
                                <FormItem label="申请原因" prop="blacklistReason">
                                    <Input v-model.trim="blackApplyForm.blacklistReason" class="w400" size="large" placeholder="请输入黑名单申请原因" type="textarea" :rows="6"/>
                                </FormItem>
                            </Form>
                            <div slot="footer" style="text-align:center;" >
                                <Button type="text" @click="cancel2">取消</Button>
                                <Button type="primary" @click="join">提交</Button>
                            </div>
                        </Modal>

                            <Form ref="drawerPartyForm" :model="drawerPartyForm" :label-width="130"
                                  :rules="formValidate" inline v-bind:disabled="this.typeCode == '0'" >

                                <Row>
                                    <FormItem label="SP名称" prop="channelId" style="width: 350px"   class="s1">
                                        <Select v-model="drawerPartyForm.channelId" filterable  placeholder="请选择" style="width: 200px" @on-change="getCarDealerById" clearable>
                                            <Option v-for="(item,index) in channelData" :value="item.channelId" :label="item.channelFullName"  :key="index" ></Option>
                                        </Select>
                                    </FormItem>

                                    <Form-item label="车商名称" prop="cardealerId" style="width: 350px" :rules="Number(this.switch)== 1 ? validDate:notValidDate" class="s1">
                                        <Select v-model="drawerPartyForm.cardealerId" filterable placeholder="请选择" style="width: 200px" @on-change="checkChannel" clearable>
                                            <Option v-for="(item,index) in data2" :value="item.cardealerId" :label="item.cardealerName"  :key="index"></Option>
                                        </Select>
                                    </Form-item>

                                    <Form-item label="状态" prop="status" style="width: 300px">
                                        <radio-group v-model="drawerPartyForm.status"  >  <!--@on-change="selectRadio"-->
                                            <radio label="00"  style="width: 90px">启用</radio>
                                            <radio label="05" >停用</radio>
                                        </radio-group>
                                    </Form-item>
                                </Row>

                                <Row>
                                    <Form-item label="开票方名称" prop="drawerPartyName" style="width: 350px">
                                        <Input type="text" v-model.trim="drawerPartyForm.drawerPartyName" clearable placeholder="请输入" style="width:200px"/>
                                    </Form-item>

                                    <Form-item label="开票方注册时间" prop="registDate" style="width:350px">

                                            <Date-picker type="date" placeholder="选择日期" v-model="drawerPartyForm.registDate" style="width:200px"  :options="options" clearable></Date-picker>

                                    </Form-item>

                                    <Form-item label="纳税人识别号" prop="taxpayerIdNumber" style="width: 300px" >
                                        <Input type="text"  clearable v-model.trim="drawerPartyForm.taxpayerIdNumber" style="width:180px" v-bind:disabled="this.typeCode == '2'" />
                                    </Form-item>

                                </Row>

                                <Row>
                                    <FormItem label="车商注册省市" prop="cardealerRegistLocation" style="width:350px;">
                                        <Cascader :data="location" v-model="drawerPartyForm.cardealerRegistLocation" style="width:200px;"
                                                  :load-data="loadData"></Cascader>
                                    </FormItem>

                                    <Form-item label="车商注册详细地址" prop="cardealerRegistAddr" >
                                        <Input type="text" v-model.trim="drawerPartyForm.cardealerRegistAddr" placeholder="请输入..."
                                               style="width: 542px"></Input>
                                    </Form-item>

                                </Row>

                                <Row>
                                    <FormItem label="开票方注册省市" prop="registLocation" style="width:350px;">
                                        <Cascader :data="location" v-model="drawerPartyForm.registLocation" style="width:200px;"
                                                  :load-data="loadData"></Cascader>
                                    </FormItem>

                                    <Form-item label="开票方注册详细地址" prop="address" >
                                        <Input type="text" v-model.trim="drawerPartyForm.address" placeholder="请输入..."
                                               style="width: 542px"></Input>
                                    </Form-item>
                                </Row>

                                <Form-item label="备注" prop="remark">
                                    <Input type="textarea" :rows="3" v-model.trim="drawerPartyForm.remark" placeholder="请输入..." style="width: 902px"></Input>
                                </Form-item>
                            </Form>


                            <Button @click="openFileUpload" size="large"
                                    style=" color: #2b85e4;background-color:white;border:none;float:right;">{{fileText}}
                            </Button>


                    </Row>

                </Card>
            </Col>
        </Row>

        <div v-if="isShowFile">
            <!--附件-->
            <file-operation  :uploadParam="uploadParam" :isInt="canUpload" :path="path" :readOnly="readOnly"></file-operation>
        </div>

    </div>

</template>


<script>
    import {formatDate} from "_c/iview/components/date-picker/util";
    import {
        saveDrawerPartyData,
        editCarDealerData,
        getCarDealerByChannelId,
        //要改
        getChannelInfobyChannelId,
        getDrawerPartyById,
        getAllSPChannels,
    } from "@/projects/afs-channel/api/drawer-party/drawerParty";
    import {
        saveBlack,
        blackCleack,
    } from "@/projects/afs-channel/api/car-dealer/dealer";
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import {getLocation} from "@/projects/afs-channel/api/common/common";
    import {getChannelBasicInfoById,} from  "@/projects/afs-channel/api/dealer/dealer";
    import FileOperation from "_p/basic/pages/image/upload-file/fileOperation.vue";
    import {
        checkFile,
    } from "_p/basic/api/image/image-upload";

    export default {
        name: "drawerParty-edit",
        components: {
            circleLoading,
            FileOperation,
        },
        data() {
            const validateTaxNum = (rule, value, callback) => {
                var reg = /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/;
                if (!reg.test(value)) {
                    callback(new Error("纳税人识别号格式有误"));
                } else {
                    callback();
                }
            };
            return {

                options: {
                    disabledDate (date) {
                        return date && date.valueOf() >= new Date();
                    }
                },

                //权限
                directManageRole:false,
                directcheckRole:false,
                commonManageRole:false,
                commoncheckRole:false,

                fileText:"上传附件",

                //附件部分
                readOnly:true,
                uploadParam: {
                    busiNo: "",
                    belongNo: "",
                    busiType: "",
                    busiData: {}
                },
                canUpload:true,
                path:"channel",

                //转圈圈
                spinShow: false,
                //车商是否选择
                validDate:[],
                validDateOld:[],
                switch:1,
                isShowFile: false,
                location:[],
                modalTitle:"",
                blackApplyVisible: false,//黑名单
                channelId:"",
                data2:[],
                loading: true,
                typeCode: 0,
                drawerPartyForm: {
                    id:"",
                    channelId:"",
                    cardealerId:"",
                    channelFullName: "",
                    cardealerName: "",
                    status: "00",
                    drawerPartyName: "",
                    taxpayerIdNumber: "",
                    remark: "",
                    registDate: "",
                    cid:"",     //关联表的id
                    //车商注册地址
                    cardealerRegistAddr: "",
                    cardealerRegistLocation:[],
                    //开票方注册地址
                    address:"",
                    registLocation:[],
                },
                submitLoading: false,
                data: [],
                //上传附件的东西
                baseData2: [{
                    expand: true,
                    title: '全部资料(0)',
                    children: [{
                        title: '车商备案影像件(0)',
                        children: [{
                            title: '其他(0)'
                        }]
                    }]
                }],
                fileFrom: {
                    productName: ""
                },

                //合作商信息
                channelData: [],
                formValidate: {
                    channelId: [
                        {required: true, message: "SP名称不能为空", trigger: "blur"}
                    ],

                    drawerPartyName: [
                        {required: true, message: "开票方名称不能为空", trigger: "blur"}
                    ],
                    taxpayerIdNumber: [
                        {required: true, message: "纳税人识别号不能为空", trigger: "change"},
                        {validator: validateTaxNum, trigger: "blur"}
                    ],
                    cardealerRegistLocation: [
                        {required: true, message: "车商注册省市不能为空", trigger: "change", type: "array"}
                    ],
                    cardealerRegistAddr: [
                        {required: true, message: "车商注册详细地址不能为空", trigger: "blur"}
                    ],
                    registLocation: [
                        {required: true, message: "开票方注册省市不能为空", trigger: "change", type: "array"}
                    ],
                    address: [
                        {required: true, message: "开票方注册详细地址不能为空", trigger: "blur"}
                    ],
                    /*remark: [
                        {required: true, message: "备注不能为空", trigger: "blur"}
                    ],*/
                    registDate: [
                        {required: true, message: "注册时间不能为空", trigger: "blur",type:"date"}
                    ],
                },
                validDate:[
                    {required: true,  message: "车商名称不能为空", trigger: "blur"}
                ],
                notValidDate:[
                    { required: false, trigger: "change"}
                ],

                //黑名单
                blackApplyForm:{
                },
                //黑名单
                blackApplyFormValidate:{
                },

            };
        },
        methods: {
            init() {
                this.getUserRole();
                this.getLocationData();
                this.typeCode=this.afs.getPageParams(this).type;
                if(this.typeCode != '1'){
                    this.getDrawerPartyInfo(this.afs.getPageParams(this).drawerPartyId,this.afs.getPageParams(this).cardealerId);
                    console.log(this.drawerPartyForm.channelId)
                   /* this.drawerPartyForm.channelId=this.afs.getPageParams(this).cardealerId+"";*/
                }
                this.getAllChannelInfo();
                if(this.typeCode != '0'){
                    this.readOnly = false;
                }
            },

            getUserRole(){
                let userRoles = this.$store.state.user.roles.toString()
                //直营管理
                if (userRoles.indexOf('ROLE_OWN_MANAGE_INVOICE') > -1 || userRoles.indexOf('ROLE_ADMIN')> -1 || userRoles.indexOf('ROLE_CHANNEL_ADMIN')> -1) {
                    this.directManageRole = true;
                    this.directcheckRole = true;
                }
                //非直营管理
                if (userRoles.indexOf('ROLE_OTHER_MANAGE_INVOICE') > -1 || userRoles.indexOf('ROLE_ADMIN')> -1 || userRoles.indexOf('ROLE_CHANNEL_ADMIN')> -1) {
                    this.commonManageRole = true;
                    this.commoncheckRole = true;
                }

            },


            // 有关省市的
            getLocationData() {
                let param = ""
                param = {
                    level: '1',
                    upperCode: '1'
                };
                getLocation(param).then((res) => {
                    if (res.code == "0000") {
                        res.data.forEach(item => {
                            // 表明是否是父节点
                            if (item.isParent) {
                                item.loading = false;
                                item.children = [];
                            }
                        })
                    }
                    this.location.push(...res.data);
                })
            },

            //调用省市的方法
            loadData(item, callback) {
                // console.log("是否调用新车")
                item.loading = true;
                getLocation({upperCode: item.value}).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (item) {
                            if (item.isParent) {
                                item.loading = false;
                                item.children = [];
                            }
                        });
                        item.children = res.data;
                        item.loading = false;
                        callback();
                    }
                })
            },

            //根据开票方id查询基本信息
            getDrawerPartyInfo(v,c){
                getDrawerPartyById(v,c).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        this.drawerPartyForm=res.data[0];
                        this.drawerPartyForm.cid=res.data[1].id;
                        if(res.data[0].status=="02"){
                            this.drawerPartyForm.status='00';
                        }
                        //省市地址赋值
                        this.drawerPartyForm.cardealerRegistLocation = [
                            this.drawerPartyForm.cardealerRegistProvince,
                            this.drawerPartyForm.cardealerRegistCity
                        ];
                        this.drawerPartyForm.registLocation = [
                            this.drawerPartyForm.registProvince,
                            this.drawerPartyForm.registCity
                        ];
                        this.drawerPartyForm.channelId=this.afs.getPageParams(this).channelId+"";
                        this.getCarDealerById();
                        this.drawerPartyForm.cardealerId=this.afs.getPageParams(this).cardealerId+"";
                    }
                })
            },

            //查所有渠道
            getAllChannelInfo(){
                console.log("查所有渠道")
                let channelBelong = null;
                if(this.commoncheckRole && !this.directcheckRole){
                    channelBelong = ['00','02']
                }else if(!this.commoncheckRole && this.directcheckRole){
                    channelBelong = ['01']
                }
                getAllSPChannels({channelBelong:channelBelong}).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                       this.channelData= res.data;
                     //  console.log(this.afs.getPageParams(this).channelId)
                        //this.drawerPartyForm.channelId = "123";
                    }
                })
            },


            //黑名单申请
            addBlackList(){
                console.log("黑名单申请开始！");
                this.modalTitle="确认将开票方加入黑名单吗？";
                this.blackApplyVisible=true;
            },
            cancel2() {
                //关闭黑名单窗口
                this.blackApplyVisible = false;
            },
            //申请加入黑名单
            join(){
                console.log("开票方黑名单保存开始！");
                let params={
                    //黑名单类型：开票方
                    blacklistType:'04',
                    //黑名单名称
                    blackName:this.drawerPartyForm.drawerPartyName,
                    //证件类型：组织机构代码
                    idType:'02',
                    idCode:this.drawerPartyForm.taxpayerIdNumber,
                    //黑名单原因
                    blacklistReason:this.blackApplyForm.blacklistReason
                }
                saveBlack(params).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success("申请成功！");
                    }
                        this.cancel2();
                })
            },

            getCarDealerById() {
                //清楚车商名称
                this.drawerPartyForm.cardealerId="";
                this.channelId = this.drawerPartyForm.channelId;
                //根据渠道id获取渠道的信息
                getChannelBasicInfoById(this.channelId).then((res) => {
                    if (res.code == "0000") {
                        this.switch  = res.data[0].choiceCardealerSwitch;
                        console.log(this.switch,"sss")
                    }
                })
                this.$refs.drawerPartyForm.fields.forEach(function (e) {
                    if (e.prop == 'validDate') {
                        e.validateMessage="";
                        e.validateState="";
                    }
                })
                getCarDealerByChannelId(this.channelId).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        this.data2 = res.data;
                        console.log(this.data2)
                    }
                });
            },

            //返回
            back() {
                console.log("返回***")

                this.afs.closeTab(this);
                this.$router.push({path: '/drawerParty'});
            },
            saveDrawerParty(){
                this.drawerPartyForm.status = '02';
                this.submitDrawerParty();
            },

            //提交
            submitDrawerParty() {
                this.loading = true;
                //目前写死 后面要改
                this.$refs.drawerPartyForm.validate(valid => {
                        if (valid) {
                //验证黑名单
                let blackParams={
                    //黑名单类型：开票方
                    blacklistType:'04',
                    //黑名单名称
                    blackName:this.drawerPartyForm.drawerPartyName,
                    //证件类型：组织机构代码
                    idType:'02',
                    idCode:this.drawerPartyForm.taxpayerIdNumber,
                };
                blackCleack(blackParams).then(res => {
                    if (res.code === "0000") {
                        if(res.weatherBlackList=="1"){
                            this.$Message.error("该开票方已存在黑名单信息库中");
                       }else if(res.weatherBlackList=="0"){
                            let time = "";
                            if(this.drawerPartyForm.registDate != null || this.drawerPartyForm.registDate  !=""){
                                time =formatDate(this.drawerPartyForm.registDate ,"yyyy-MM-dd")
                            }
                            let param = {
                                drawerParty: {
                                    id: this.drawerPartyForm.id,
                                    status: this.drawerPartyForm.status,
                                    drawerPartyName: this.drawerPartyForm.drawerPartyName.replace(/\s*/g,""),
                                    registDate: time,
                                    cardealerRegistAddr: this.drawerPartyForm.cardealerRegistAddr,
                                    registProvince: this.drawerPartyForm.registProvince,
                                    taxpayerIdNumber: this.drawerPartyForm.taxpayerIdNumber.replace(/\s*/g,""),
                                    remark: this.drawerPartyForm.remark,

                                    //车商注册地
                                    cardealerRegistProvince:this.drawerPartyForm.cardealerRegistLocation[0],
                                    cardealerRegistCity:this.drawerPartyForm.cardealerRegistLocation[1],
                                    cardealerRegistAddr: this.drawerPartyForm.cardealerRegistAddr,
                                    //开票方注册地址
                                    registProvince:this.drawerPartyForm.registLocation[0],
                                    registCity:this.drawerPartyForm.registLocation[1],
                                    address:this.drawerPartyForm.address,
                                },
                                channelCoopeDrawerParty: {
                                    id: this.drawerPartyForm.cid,
                                    cardealerId: this.drawerPartyForm.cardealerId,
                                    channelId: this.drawerPartyForm.channelId,
                                },
                            };
                            this.spinShow= true;
                            saveDrawerPartyData(param).then(res => {
                                this.loading = false;
                                if (res.code === "0000") {
                                    this.drawerPartyForm.id=res.data[0].id;
                                    this.drawerPartyForm.cid=res.data[1].id;
                                    this.spinShow= false;
                                    this.$Message.success("操作成功");
                                    if(this.drawerPartyForm.status != '02'){
                                        this.afs.closeTab(this);
                                        this.$router.push({path: '/drawerParty'});
                                    }else {
                                        this.drawerPartyForm.status = '00';
                                    }
                                }
                            }).catch(() => {
                                this.spinShow= false;
                            });
                        }
                    }
                }).catch(() => {
                    this.$Message.success("黑名单验证失败！");
                    this.spinShow= false;
                    return false;
                });
                        }
                });
            },
            checkChannel(){
                console.log("**")
                if(drawerPartyForm.channelId==""){
                    this.$Message.error("请勾选新车授权区域");
                    return false;
                }
            },


            openFileUpload() {
                // this.isShowFile = true;
                // this.isShowFile = true;
                this.isShowFile = !this.isShowFile;
                if (this.isShowFile) {
                    this.fileText = "关闭附件";
                } else {
                    this.fileText = "上传附件";
                }

                if(this.drawerPartyForm.id && this.isShowFile){
                    this.initGetFilterParams();
                }
            },
            initGetFilterParams() {
                this.uploadParam.busiNo = this.drawerPartyForm.id;
                this.uploadParam.belongNo = this.drawerPartyForm.id
                this.uploadParam.busiData = {};
                this.uploadParam.busiType = "drawerParty";
            },

            //影像件校验
            checkFileMethed() {
                console.log(this.uploadParam.busiNo)
                if (this.drawerPartyForm.id) {
                    this.initGetFilterParams();
                    checkFile(this.uploadParam).then(res => {
                        if (res.code === '0000') {
                            this.submitDrawerParty();
                        }
                    }).catch(() => {
                        this.$Message.error("请录入影像资料！");
                    });
                } else {
                    this.$Message.error("请先保存基本信息!");
                }
            },

        },
        mounted() {
            this.init();
        },
    };
</script>
